package communication;

public class Producer implements Runnable {

    final Clerk clerk;

    @Override
    public void run() {
        while (true) {
            synchronized (clerk) {
                if (clerk.getProduction() == Clerk.MAX_PRODUCTION) {
                    try {
                        clerk.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    this.produce(clerk);
                    clerk.notify();
                }
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    public void produce(Clerk clerk) {
        clerk.setProduction(clerk.getProduction() + 1);
        System.out.println(Thread.currentThread().getName() +
                " -- 生产ing... 产品余量为" + clerk.getProduction());
    }
}
